package com.desin.modle.datastruct.myleetcode;

public class Solution1 {
    private Integer m;
    private Integer n;
    private boolean[][] marked;
    private char[][] board;
    private String word;
    private int[][] direction = new int[][]{{-1,0},{1,0},{0,-1},{0,1}};
    public boolean exist(char[][] board, String word) {
        if(board==null||board.length==0||board[0].length==0){
            return false;
        }
        this.m= board.length;
        this.n = board[0].length;
        this.marked=new boolean[m][n];
        this.board = board;
        this.word = word;
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(dfs(i,j,0)){
                    return true;
                }
            }
        }
        return false;
    }

    private boolean dfs(int i, int j, int start) {
        if(start==word.length()-1){
            return board[i][j]==word.charAt(start);
        }
        if(board[i][j]==word.charAt(start)){
            marked[i][j]=true;
            for(int k=0;k<4;k++){
                int x = i+direction[k][0];
                int y = j+direction[k][1];
                if(inArea(x,y)&&!marked[x][y]){
                    if(dfs(x,y,start+1)){
                        return true;
                    }
                }
            }
            marked[i][j]=false;
        }
        return false;
    }

    private boolean inArea(int x, int y) {
        return x>=0&&x<m&&y>=0&&y<n;
    }
}
